package com.example.redis.tool;


import redis.clients.jedis.Jedis;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @author:xuecx
 * @descript:<p>利用redis实现分布式锁</p>
 * @date:2018/10/12
 */
public class RedisLock {
    private static final String LOCK_SUCCESS = "OK";
    //即当key不存在时，我们进行set操作；若key已经存在，则不做任何操作
    private static final String SET_IF_NOT_EXIST = "NX";
    //设置过期参数
    private static final String SET_WITH_EXPIRE_TIME = "PX";
    private static final Long RELEASE_SUCCESS = 1L;

    /**
     * 加锁
     *
     * @param jedis
     * @param lockKey
     * @param requestId
     * @param expire
     * @return
     */
    public static boolean lock(Jedis jedis, String lockKey, String requestId, int expire) {
        String set = jedis.set(lockKey, requestId,SET_IF_NOT_EXIST,SET_WITH_EXPIRE_TIME,expire);
        System.out.println("获取锁"+set);
        if (LOCK_SUCCESS.equals(set)) {
            System.out.println("获取锁"+requestId+"成功");
            return true;
        }
        return false;
    }

    /**
     * 释放锁
     *
     * @param jedis
     * @param lockKey
     * @param requestId
     * @return
     */
    public static boolean unLock(Jedis jedis, String lockKey, String requestId) {
        //判断要删除的锁是否是锁给定的请求，如果是则删除，否则不删除， //这里要保证原子性
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));
        if (RELEASE_SUCCESS.equals(result)) {
            System.out.println("释放锁"+requestId);
            return true;
        }
        System.out.println("释放锁"+requestId+"失败");
        return false;
    }
}
